using System;
using System.IO;

namespace brainfucker
{
	public class Interpreter
	{
		public TextReader Input = Console.In;
		public TextWriter Output = Console.Out;
		
		private int[] array;
		private int index;
        private int array_size;
		
		public Interpreter() : this(30000, 0)
		{
		}
		
		public Interpreter(int array_size, int offset)
		{
		    this.array_size = array_size;
		    index = offset;
		}
		
		public static void Analyze(string source, out int size, out int offset)
		{
		    size = 1;
		    offset = 0;
		    int cell = 1;
		    foreach(char c in source.ToCharArray()) {
		        switch(c) {
		        case '>':
		            if(cell == size) {
		                size++;
		            }
		            cell++;
		            break;
		        case '<':
		            cell--;
		            if(cell == offset) {
		                size++;
		                offset--;
		            }
		            break;
		        }
		    }
		    offset = Math.Abs(offset);
		}
		
		public void Interpret(string source)
		{
		    array = new int[array_size];
            bool outputted = false;
            char last_char = '\n';
            char [] chars = source.ToCharArray();
		    int i = 0;
		    while(i < chars.Length) {
		        switch(chars[i]) {
		        case '>':
		            index++;
		            break;
		        case '<':
		            index--;
		            break;
		        case '+':
		            array[index]++;
		            break;
		        case '-':
		            array[index]--;
		            break;
		        case '.':
		            outputted = true;
                    last_char = (char)array[index];
                    Output.Write(last_char);
		            break;
		        case ',':
		            array[index] = Input.Read();
		            break;
		        case '[':
		            if(array[index] <= 0) {
    		            int loops = 1;
    		            while(loops > 0) {
    		                i++;
    		                if(chars[i] == ']') {
    		                    loops--;
    		                } else if(chars[i] == '[') {
    		                    loops++;
    		                }
    		            }
		            }
		            break;
		        case ']':
		            if(array[index] > 0) {
    		            int loops = 1;
    		            while(loops > 0) {
    		                i--;
    		                if(chars[i] == '[') {
    		                    loops--;
    		                } else if(chars[i] == ']') {
    		                    loops++;
    		                }
    		            }
		            }
		            break;
		        }
		        i++;
		    }
            if(outputted && last_char != '\n' && last_char != '\r') {
                Output.WriteLine();
            }
		}
	}
}
